<?php


namespace app\wechat\controller;


use app\BaseController;
use app\common\model\User;
use app\common\model\Coupon;
use app\common\model\UserIntegral;
use app\wechat\validate\TokenGet;
use think\cache\driver\Redis;

//use think\Db;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Cache;
use think\route\dispatch\Controller;
use think\facade\Db;

class Token extends BaseController
{
    protected $code;
    protected $wxAppId;
    protected $wxAppSecret;
    protected $wxLoginUrl;
    protected $ip;
    protected $user;
    protected $is_new=1;
    protected $password="teacher123";
    protected $head_img="无头像";

//    function __construct()
//    {
//
//    }

    public function getToken()
    {
        // $cachedValue['uid'] = 3;
        // $cachedValue['userType'] = 2;
        // Cache::set("567",serialize($cachedValue),2592000);
        // return show(1,'注册成功');
        $this->code = input('code');
        $this->head_img = input('head_img');
        $password = input('password');
        // $this->wxAppId = config('wx.app_id');
        // $this->wxAppSecret = config('wx.app_secret');
        // $this->wxLoginUrl = sprintf(config('wx.login_url'), $this->wxAppId, $this->wxAppSecret, $this->code);
        // $this->ip = $_SERVER['REMOTE_ADDR'];
        // try {
        //     validate(TokenGet::class)->check([
        //         'code' => $this->code,
        //     ]);
        // } catch (ValidateException $e) {
        //     return show(0, $e->getError());
        // }
        // $result = curl_get($this->wxLoginUrl);
        // $wxResult = json_decode($result, true);
        // // $wxResult['session_key']="o2iPEDo1D29YB2/hJQFCkg==";
        // // $wxResult['openid']="o706y7QRo7coH_RcmqHP8hFdBhms/hJQFCkg==";
        // if (empty($wxResult)) {
        //     return show(0, '获取open_id报错,微信服务内部报错');
        // } else {
        //     $loginFail = array_key_exists('errcode', $wxResult);
        //     if ($loginFail) {
        //         return show(0, $wxResult['errmsg']);
        //     }
        // }
        // $token = $this->grantToken($wxResult);
        $token = $this->grantTokenId($password);
        if ($token == false) {
            return show(0, '登录失败');
        }
        if($this->is_new==2&&$this->password==$password){
            return show(4, '请求成功', ['token' => $token,'user'=>$this->user]);
        }
        return show(1, '请求成功', ['token' => $token,'user'=>$this->user]);
    }

    private function grantToken($wxResult)
    {
        $openid = $wxResult['openid'];
        $user = User::getByOpenID($openid);
        if ($user) {
            $this->user=$user;
            $uid = $user['id'];
            $type = $user['type'];
        } else {
            $uid = $this->newUser($openid);
            if ($uid == false) {
                return false;
            }
            $type=1;
        }
        //生成保存的数据
        $cachedValue = $this->prepareCachedValue($wxResult, $uid,$type);
        //保存缓存
        $token = $this->saveToCache($cachedValue);
        return $token;

    }
    private function grantTokenId($id)
    {
        $user = User::getByID($id);
         $this->user=$user;
            $uid = $user['id'];
            $type = $user['type'];
        $wxResult['open_id']=123;
        //生成保存的数据
        $cachedValue = $this->prepareCachedValue($wxResult, $uid,$type);
        //保存缓存
        $token = $this->saveToCache($cachedValue);
        return $token;

    }

    //写入缓存
    private function saveToCache($cachedValue)
    {
        //32个字符组成一组随机字符串
        $randChars = md5(date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT));
        //用三组字符串,进行md5加密
        Cache::set($randChars,serialize($cachedValue),2592000);
        return $randChars;
    }

    private function prepareCachedValue($wxResult, $uid,$type)
    {
        $cachedValue = $wxResult;
        $cachedValue['uid'] = $uid;
        $cachedValue['userType'] = $type;
        $cachedValue['scope'] = 16;
        return $cachedValue;
    }

    /**\
     * @param $openid
     * @return mixed
     * 去创建新用户
     */
    private function newUser($openid)
    {
        $thirty = mktime(0, 0, 0, date('m'), date('d') + 31, date('Y')) - 1;
        $abc = city($this->ip);
        \think\facade\Db::startTrans();
        //起名字
        $one=array_rand(User::ONE_CIKU,1);
        $two=array_rand(User::TWO_CIKU,1);
        $nickname=User::ONE_CIKU[$one]."的".User::TWO_CIKU[$two];
        try {
            $nickname_count=Db::name('user')
                ->where('nickname','like',$nickname."%")
                ->count();
            if ($nickname_count){
                $nickname=$nickname.$nickname_count;
            }
            $user = \think\facade\Db::name('user')
                ->insertGetId([
                    'nickname' => $nickname,
                    'head_img' => $this->head_img,
                    'openid' => $openid,
                    'create_time' => time(),
                    'ip' => $this->ip,
                    'country' => $abc['nation'],
                    'province' => $abc['region'],
                    'city' => $abc['city'],
                ]);
            $this->is_new=2;
            $new_user['id']=$user;
            $this->user=$new_user;
            \think\facade\Db::commit();
            return $user;
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return false;
        }
    }
}